package com.demo.youxuanmall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.youxuanmall.entity.Category;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.service.CategoryService;
import com.demo.youxuanmall.service.ProductService;
import com.demo.youxuanmall.service.SystemSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Controller
public class ProductController extends BaseController {

    private final ProductService productService;
    private final CategoryService categoryService;

    public ProductController(SystemSettingService systemSettingService,
                          ProductService productService,
                          CategoryService categoryService) {
        super(systemSettingService);
        this.productService = productService;
        this.categoryService = categoryService;
    }

    @GetMapping("/products")
    public String productList(Model model, @RequestParam(required = false) Long categoryId,
                               @RequestParam(required = false) String keyword) {
        List<Category> categories = categoryService.listEnabledCategories();
        model.addAttribute("categories", categories);
        
        List<Product> products;
        if (categoryId != null) {
            // 按分类查询
            products = productService.getProductsByCategory(categoryId);
            model.addAttribute("currentCategoryId", categoryId);
        } else if (keyword != null && !keyword.trim().isEmpty()) {
            // 按关键词搜索
            products = productService.searchProducts(keyword);
            model.addAttribute("keyword", keyword);
        } else {
            // 查询所有商品
            products = productService.listEnabledProducts();
        }
        
        model.addAttribute("products", products);
        return "product/list";
    }

    @GetMapping("/product/detail/{id}")
    public String productDetail(@PathVariable("id") Long id, Model model) {
        Product product = productService.getProductById(id);
        if (product == null || product.getStatus() != 1 || product.getIsDeleted() == 1) {
            return "redirect:/404";
        }
        
        // 查询相关推荐商品（同类别的其他商品）
        List<Product> relatedProducts = productService.getRelatedProducts(product.getCategoryId(), id, 4);
        
        model.addAttribute("product", product);
        model.addAttribute("relatedProducts", relatedProducts);
        
        return "product/detail";
    }
} 